package com.smartview.common.filter;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.smartview.jboss.spring.dto.UserDTO;


public class SecurityFilter implements Filter {

	private FilterConfig filterConfig;
	private Pattern pNoSecure;
	private Pattern pSecureNeed;
	
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
		
		pNoSecure = Pattern.compile(filterConfig.getInitParameter("NO_SECURE_PAGE"));
		pSecureNeed = Pattern.compile(filterConfig.getInitParameter("SECURE_NEED_PAGE"));
	}
	
	public void destroy() {
		this.filterConfig = null;
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
	throws IOException, ServletException{
		
		System.out.println("Security Filter");
		HttpServletRequest req = (HttpServletRequest)request;		
		String uri = req.getRequestURI();
		
		boolean isNoSecurePage = pNoSecure.matcher(uri).matches();
		boolean isSecureNeedPage = pSecureNeed.matcher(uri).matches();
	
		if( !isNoSecurePage){
			UserDTO info = (UserDTO)req.getSession().getAttribute("userInfo");
			if(info == null){
				RequestDispatcher rd = request.getRequestDispatcher("/spirng/loginProc.do");
				request.setAttribute("msg","You can use it after Login ");
				
				rd.forward(request, response);
				return;
			}
		}

		chain.doFilter(request, response);
	}

}